package com.whfc.iot.gas.server;

import com.whfc.common.enums.DeviceType;
import com.whfc.gas.entity.GasMsg;
import com.whfc.iot.gas.processor.GasUpMsgProcessor;
import com.whfc.iot.gas.processor.GasUpMsgProcessorFactory;
import com.whfc.iot.handler.DefaultServerHandler;
import com.whfc.iot.session.Session;
import com.whfc.iot.session.SessionManager;
import com.whfc.iot.util.LoggingUtil;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@ChannelHandler.Sharable
@Component
public class GasServerHandler extends DefaultServerHandler {

    private Logger logger = LoggerFactory.getLogger(GasServerHandler.class);

    @Autowired
    private GasUpMsgProcessorFactory processorFactory;

    @Autowired
    private SessionManager sessionManager;

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        logger.info("{}", LoggingUtil.format(ctx, "CHANNEL_READ", msg));
        try {
            GasMsg reqMsg = (GasMsg) msg;
            String deviceCode = reqMsg.getMac();
            Integer deviceType = DeviceType.gas.getValue();

            //构建session
            Session session = sessionManager.getSessionByDeviceSn(deviceCode);
            if (session == null) {
                session = sessionManager.createSession(deviceType, deviceCode, ctx.channel());
            }
            //当前channel与session中的channel不一致
            else if (!session.getChannel().equals(ctx.channel())) {
                session.getChannel().close().addListener(future -> {
                    logger.info("旧连接关闭,deviceId={},isDone={},isSuccess={}", deviceCode, future.isDone(), future.isSuccess());
                });
                session = sessionManager.createSession(deviceType, deviceCode, ctx.channel());
            }
            logger.info("gas,deviceCode:{},channelId:{}", deviceCode, ctx.channel().id());

            //处理数据
            GasUpMsgProcessor processor = processorFactory.getMsgProcessor(reqMsg.getFrameType());
            if (processor != null) {
                processor.processMsg(reqMsg);
            }

        } catch (Throwable ex) {
            logger.error("处理消息失败", ex);
        }
    }
}
